package com.watermeter.android.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.oa.android.R;
import com.watermeter.android.adapter.RouteAdapter;
import com.watermeter.android.entry.DnowDate;
import com.watermeter.android.entry.DownRoute;
import com.watermeter.android.entry.Rows;
import com.watermeter.android.entry.UpRoute;
import com.watermeter.android.entry.curstorInfo;
import com.watermeter.android.utils.UConstants;
import com.watermeter.android.utils.Util;
import com.watermeter.android.view.SelectDatePopupWindow;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;


/**
 * 下载路线
 *
 * @author -zouqh
 */
public class DownloadRouteActivity extends Activity implements OnClickListener {

    private ImageView close;
    private TextView title;
    private TextView rigth;
    private TextView show;
    private ListView routeListview;
    ProgressDialog dialog;
    private List<Rows> rowsList;
    private RouteAdapter adapter;
    private Calendar calendar;//日历
    private int yeas;//年
    private String mouth;//月
    public DbManager.DaoConfig daoConfig;
    private List<DownRoute> downRouteList;
    public List<DnowDate> dateList;
    public String time;
    public static DownloadRouteActivity activity;
    private SelectDatePopupWindow datePop;
    private String strTime[] = new String[3];

    private Dialog Jdialog;

    private List<Rows> roList;
    private List<UpRoute> upRouteList;
    private String deleteTime;//需要删除的月份数据
    private boolean isDelete;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        activity = this;
        setContentView(R.layout.donload_route_activity);
        calendar = Calendar.getInstance();
        yeas = calendar.get(Calendar.YEAR);
        int m = calendar.get(Calendar.MONTH) + 1;
        if (m < 10) {
            mouth = "0" + m;
        } else {
            mouth = m + "";
        }
        Util.printLog("yeas====", yeas + "");
        Util.printLog("mouth====", mouth + "");
        time = yeas + mouth;
        close = (ImageView) findViewById(R.id.close);
        title = (TextView) findViewById(R.id.title_text);
        rigth = (TextView) findViewById(R.id.ritgh_text);
        show = (TextView) findViewById(R.id.show);
//        show.setText(yeas + "年" + mouth + "月线路数据");
        routeListview = (ListView) findViewById(R.id.routeListview);
        title.setText("下载路线");
        rigth.setVisibility(View.VISIBLE);
        rigth.setOnClickListener(this);
        rigth.setText(time);
        close.setOnClickListener(this);
        rigth.setOnClickListener(this);
        rowsList = new ArrayList<>();

        strTime[0] = Util.getMosOne(yeas, m);
        strTime[1] = time;
        strTime[2] = Util.getNextOne(yeas, m);
        getdownDate();
        if (dateList == null) {
            dateList = new ArrayList<>();
        }
        adapter = new RouteAdapter(this, rowsList, yeas + mouth, dateList);
        routeListview.setAdapter(adapter);

        getRoute(time);


    }

    private void getDB() {
        daoConfig = new DbManager.DaoConfig()
                // 数据库的名字
                .setDbName("CB_DATE")
                // 保存到指定路径
                .setDbDir(new
                        File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/CB/"))
                // 数据库的版本号
                .setDbVersion(1)
                // 数据库版本更新监听
                .setDbUpgradeListener(new DbManager.DbUpgradeListener() {
                    @Override
                    public void onUpgrade(DbManager arg0, int arg1, int arg2) {
                        LogUtil.e("数据库版本更新了！");
                    }
                });
    }

    /**
     * 提示
     */
    private void pointDialog(String str, final String cbline, final int postion) {
        LayoutInflater inflaterDl = LayoutInflater.from(this);
        View layout = inflaterDl.inflate(R.layout.exti_dialog,
                null);
        // 对话框
        Jdialog = new Dialog(this);
        Jdialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        Jdialog.show();

        Jdialog.setContentView(layout);
        TextView sure = (TextView) layout.findViewById(R.id.sureExti);
        TextView cancle = (TextView) layout.findViewById(R.id.cancleExti);
        TextView dialogTitle = (TextView) layout.findViewById(R.id.dialogTitle);
        dialogTitle.setText(str);
        sure.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Jdialog.cancel();
                getDownRoute(cbline, postion);


            }
        });
        cancle.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Jdialog.dismiss();
            }
        });

    }


    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        Intent intent;
        switch (v.getId()) {
            case R.id.close:
                finish();
                break;

            case R.id.ritgh_text:
                datePop = new SelectDatePopupWindow(this, strTime, rigth, 1);
                datePop.showAsDropDown(v, Gravity.TOP | Gravity.RIGHT, 0,
                        Util.px2dip(this, 70));
                break;
            default:
                break;
        }
    }

    public void setReh(String t) {
        time = t;
        rowsList = new ArrayList<>();
        dateList = new ArrayList<>();
        getdownDate();
        adapter = new RouteAdapter(this, rowsList, time, dateList);
        routeListview.setAdapter(adapter);
        getRoute(time);
    }


    //获取抄表路线
    private void getRoute(final String mouth) {
        dialog = ProgressDialog.show(this, null, "加载中...", true, false);
        RequestParams params = new RequestParams(UConstants.GET_CB_ROUTE);
        params.addBodyParameter("LKind", "CBJ");
        params.addBodyParameter("CBY", UConstants.EmpId);
        params.addBodyParameter("SMON", mouth);
        Util.printLog("SMON--------------", mouth);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getMerchants------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        boolean success = object.getBoolean("success");
//                        String msg = object.getString("msg");
                        if (success) {
                            getJson(object.getString("rows").toString());
                        }
//                        Toast.makeText(x.app(), msg, Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                dialog.dismiss();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "获取数据失败！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                dialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void getJson(String rels) throws JSONException {
        JSONArray jsonArray = new JSONArray(rels);
        if (jsonArray.length() > 0) {
            for (int i = 0; i < jsonArray.length(); i++) {
                Rows rows = new Rows();
                rows.setCBY(jsonArray.getJSONObject(i).getString("CBY"));
                rows.setID(jsonArray.getJSONObject(i).getString("ID"));
                rows.setNAME(jsonArray.getJSONObject(i).getString("NAME"));
                rows.setTOPLINE(jsonArray.getJSONObject(i).getString("TOPLINE"));
                rowsList.add(rows);
            }
            adapter.notifyDataSetChanged();
        }

    }


    /**
     * 保存数据
     */
    private void saveRoute(int postion, int num) {

        DbManager manager = x.getDb(daoConfig);
        try {
            //创建对象，用来生成表
            Rows info = rowsList.get(postion);
            info.setMOTH(time);
            info.setYCBNUM(num);
            manager.saveOrUpdate(info);
//
//            manager.save(info);

        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载数据线先判断是否是本月的数据
     */
    public void getDown(String cbline, int postion) {
        int a = 0;
        int b = 0;

        getRoute();
        if (roList != null && roList.size() > 0) {
            if (roList.get(0).getMOTH().equals(time)) {
                isDelete=false;
                getDownRoute(cbline, postion);
            } else {
                for (int i = 0; i < roList.size(); i++) {
                    a += roList.get(i).getYCBNUM();
                    b += roList.get(i).getSCBNUM();
                }

                if (a > b) {
                    isDelete=true;
                    pointDialog("您当前月份还有线路未完成抄表,继续下载会被删除所有本地数据",cbline,postion);
                } else {
                    selecteDate();
                    if (upRouteList!=null&&upRouteList.size()>0){
                        isDelete=true;
                        pointDialog("您当前月份还有抄表数据没有上传,继续下载会被删除",cbline,postion);
                    }else{
                        isDelete=true;
                        pointDialog("您当前月份抄表路线已完成,继续下载会被删除所有本地数据",cbline,postion);
                    }

                }

            }
        } else {
            isDelete=false;
            getDownRoute(cbline, postion);
        }
    }


    //下载抄表路线
    public void getDownRoute(final String cbline, final int postion) {
        dialog = ProgressDialog.show(this, null, "下载中...", true, false);
        RequestParams params = new RequestParams(UConstants.GET_CB_DATE);
        params.addBodyParameter("CBLINE", cbline);
        params.addBodyParameter("SMON", time);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getDownRoute------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        boolean success = object.getBoolean("success");
//                        String msg = object.getString("msg");
                        if (success) {
                            if (isDelete){
                                deleteDate();
                                Log.i("删除数据","AAAAAAAAAAAAAAAAAAAA");
                            }
                            Gson gson = new Gson();
                            Type lt = new TypeToken<List<DownRoute>>() {
                            }.getType();
                            downRouteList = gson.fromJson(object.getString("rows").toString(), lt);
                            if (downRouteList != null && downRouteList.size() > 0) {
                                System.out.println("downRouteList.size()==" + downRouteList.size());
                                saveRouteDate();
                                saveDownRoute(cbline);
                                saveRoute(postion, downRouteList.size());
                            } else {

                            }
                        }
//                        Toast.makeText(x.app(), msg, Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                dialog.dismiss();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "获取数据失败！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                dialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 保存路线数据
     */
    private void saveRouteDate() {

        DbManager manager = x.getDb(daoConfig);
        try {
            //创建对象，用来生成表
//            manager.delete(DownRoute.class);
            manager.saveOrUpdate(downRouteList);
            List<DownRoute> lis = manager.selector(DownRoute.class).findAll();
            if (lis != null) {
                System.out.println("CCCCCCCCCCCC" + lis.get(0));
                System.out.println("CCCCCCCCCCCC" + lis.size());
            }

        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存路线数据
     */
    private void saveDownRoute(String string) {

        DbManager manager = x.getDb(daoConfig);
        try {
            //创建对象，用来生成表
            DnowDate date = new DnowDate();
            date.setDateTime(time);
            date.setTouteId(string);
            manager.saveOrUpdate(date);
            getdownDate();
            adapter.notifyDataSetChanged();

        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取已经下载的路线
     */
    private void getdownDate() {
//
        DbManager manager = x.getDb(daoConfig);
        try {
            dateList = manager.selector(DnowDate.class).findAll();

            if (null != dateList && dateList.size() > 0) {
                System.out.println("lis========" + dateList);

            } else {
                System.out.println("getdownDate");
            }

        } catch (DbException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取下载线路
     */
    private void getRoute() {
        DbManager manager = x.getDb(daoConfig);
        try {
            //创建对象，用来生成表
            roList = manager.selector(Rows.class).findAll();
//            Selector<Lis> limit = manager.selector(Lishi.class).o;

            if (null != roList && roList.size() > 0) {
                Util.printLog("DcbActivity---------getRoute", roList.size() + "");
//                lishis.addAll(lis);
                System.out.println(roList.get(0).getCBY());
//                adpter.notifyDataSetChanged();

            }

        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除本地所有数据
     */
    private void deleteDate() {
//
        DbManager manager = x.getDb(daoConfig);
        try {
            manager.delete(curstorInfo.class);
            manager.delete(Rows.class);
            manager.delete(UpRoute.class);
            manager.delete(DnowDate.class);
            manager.delete(DownRoute.class);

        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获已抄表数据
     */
    private void selecteDate() {
//
        DbManager manager = x.getDb(daoConfig);
        try {
            upRouteList= manager.selector(UpRoute.class).findAll();

        } catch (DbException e) {
            e.printStackTrace();
        }
    }

}
